package com.derekandbritt.booST.gps;

import com.derekandbritt.booST.preferences.Preferences;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

public class GPSService extends Service {

	private volatile Looper serviceLooper;
	
	private GPSListener listener = new GPSListener();
	
	protected Context context;
	
	public static void startGPS(Context context) {
    	Log.i("com.derekandbritt.booST.gps", "creating booST's GPS intent");
        Intent svc = new Intent(context, GPSService.class);
        //TODO read this from preferences
        svc.putExtra("polling_interval", 120000);
        svc.putExtra("polling_distance", 4);
        Log.i("com.derekandbritt.booST.gps", "starting booST's GPS service");
        context.startService(svc);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

    public void onCreate() {
    	
    	Log.i("com.derekandbritt.booST.gps", "Starting up the booST GPS Service");
    	
    	HandlerThread thread = new HandlerThread("booST_GPS_Service");
        thread.start();
        context = this;
        serviceLooper = thread.getLooper();
           
    }

    public void onStart(Intent intent, int startId) {
    	
    	LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    	locationManager.removeUpdates(listener);
    	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, listener, serviceLooper);
    }

    public void onDestroy() {
    	Log.i("com.derekandbritt.booST.gps", "Shutting down the booST GPS Service");
    	serviceLooper.quit();
    }
    
    private class GPSListener implements LocationListener {

		public void onLocationChanged(Location location) {
			Log.i("com.derekandbritt.booST.gps", "Current Location: " + location.toString());
			
			SharedPreferences prefs = context.getSharedPreferences(Preferences.BOOST_PREFS, 0);
			String userId = prefs.getString(Preferences.USER_ID_PREF, null);
			if(userId == null || userId.equals("")) {
				Log.i("com.derekandbritt.booST.gps", "No user has been defined so the energyLevel cannot be computed");
				return;
			}
			
			//TODO compute energyHeuristics -> update booST Energy!

		}

		public void onProviderDisabled(String s) {
			Log.i("com.derekandbritt.booST.gps", "GPS Disabled");
		}

		public void onProviderEnabled(String s) {
			Log.i("com.derekandbritt.booST.gps", "GPS Enabled");
		}

		public void onStatusChanged(String s, int i, Bundle bundle) {
			Log.i("com.derekandbritt.booST.gps", "GPS Status Changed");	
		}
    	
    }
}
